package com.good.child.http;

import android.text.TextUtils;

import com.good.child.config.Constants;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.ObservableResponse;
import com.yimidida.library.base.LibraryApplication;
import com.yimidida.library.http.BaseLogical;
import com.yimidida.library.utils.LogUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Create on: 2024/7/31
 * by Mr.Zhu
 * Description: 请求基类
 */
public class AppBaseLogical extends BaseLogical {
    public static final int SUCCESS_CODE = 200;


    /**
     * post 请求
     * content type   json
     *
     * @param url
     * @param obj
     * @param observer
     */
    @Override
    protected void requestStringForPostNew(String url, Object obj, Observer<Response<String>> observer) {
        Map<String, String> map = (Map<String, String>) obj;
        //添加公共参数....source=android&appVersion=100&
        Map<Object, Object> params = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.put(entry.getKey(), entry.getValue());
        }
        String token = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_ID, "");
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(params));
        OkGo.<String>post(url)
                .converter(new StringConvert())
                .upRequestBody(body)
                .headers("appType", "android")
                .headers("Authorization", "Bearer " + token)
                .adapt(new ObservableResponse<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * 登录请求
     * content type   json
     *
     * @param url
     * @param obj
     * @param observer
     */
    protected void requestStringForLogin(String url, Object obj, Observer<Response<String>> observer) {
        Map<String, String> map = (Map<String, String>) obj;
        HttpParams params = new HttpParams();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.put(entry.getKey(), entry.getValue());
        }
        String token = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_ID, "");
        OkGo.<String>get(url)
                .converter(new StringConvert())
                .params(params)
                .headers("Authorization", "Bearer " + token)
                .adapt(new ObservableResponse<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }


    /**
     * post请求
     *
     * @param url
     * @param obj
     * @param observer
     */
    @Override
    protected void requestStringForPost(String url, Object obj, Observer<Response<String>> observer) {
//        super.requestStringForPost(url, obj, observer);
        Map<String, String> map = (Map<String, String>) obj;
        //添加公共参数....source=android&appVersion=100&
        Map<Object, Object> params = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.put(entry.getKey(), entry.getValue());
        }
        String tokenID = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_ID, "");
        String tokenType = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_TYPE, "");
        OkGo.<String>post(url)
                .converter(new StringConvert())
                .headers("blade-auth", tokenType + " " + tokenID)
                .upJson(new Gson().toJson(params))
                .adapt(new ObservableResponse<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Override
    protected void requestStringForPostParam(String url, Object obj, Observer<Response<String>> observer) {
        Map<String, String> map = (Map<String, String>) obj;
        HttpParams params = new HttpParams();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            params.put(entry.getKey(), entry.getValue());
        }
        String tokenID = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_ID, "");
        String tokenType = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_TYPE, "");
        OkGo.<String>post(url)
                .converter(new StringConvert())
                .params(params)
                .headers("blade-auth", tokenType + " " + tokenID)
                .adapt(new ObservableResponse<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }


    /**
     * get请求获取数据--无参数
     *
     * @param url
     */
    public void requestStringForGet(String url, Observer<Response<String>> observer) {
        if (Constants.token.isEmpty()) {
            Constants.token = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_ID, "");
        }
        OkGo.<String>get(url)
                .converter(new StringConvert())
                .headers("Authorization", "Bearer " + Constants.token)
                .adapt(new ObservableResponse<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * get请求获取数据
     *
     * @param url
     */
    public void requestStringForGet(String url, Map<String, String> params, Observer<Response<String>> observer) {
        String requestUrl = sendGetRequest(url, params);
        requestStringForGet(requestUrl, observer);
    }

    public static String sendGetRequest(String baseUrl, Map<String, String> params) {
        StringBuilder query = new StringBuilder();
        Set<Map.Entry<String, String>> entrySet = params.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            if (query.length() > 0) {
                query.append("&");
            }
            query.append(entry.getKey()).append("=").append(entry.getValue());
        }
        String urlString = baseUrl + "?" + query.toString();
        return urlString;
    }

    /**
     * 上传文件
     *
     * @param url
     * @param mSelectList
     * @param observer
     */
    public void requestFileForPost(String url, List<String> mSelectList, String content, Observer<Response<String>> observer) {
        String token = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_ID, "");
        List<File> fileList = new ArrayList<>();
        for (String path : mSelectList) {
            LogUtils.showLog("zhu", path);
            if (TextUtils.isEmpty(path)) {
                continue;
            }
            File file = new File(path);
            fileList.add(file);
        }
        OkGo.<String>post(url)
                .converter(new StringConvert())
                .isMultipart(true)
                .params("content", content)
                .addFileParams("files", fileList)
                .headers("Authorization", "Bearer " + token)
                .adapt(new ObservableResponse<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);


    }

    public void updateUserInfo(String url, List<String> mSelectList, String deviceCode, String nikeName, Observer<Response<String>> observer) {
        if (mSelectList == null && TextUtils.isEmpty(nikeName)) {
            return;
        }
        String token = (String) LibraryApplication.getSharedata().getData(Constants.LOGIN.TOKEN_ID, "");
        if (mSelectList != null) {
            List<File> fileList = new ArrayList<>();
            for (String path : mSelectList) {
                LogUtils.showLog("zhu", path);
                if (TextUtils.isEmpty(path)) {
                    continue;
                }
                File file = new File(path);
                fileList.add(file);
            }
            OkGo.<String>post(url)
                    .converter(new StringConvert())
                    .isMultipart(true)
                    .params("deviceCode", deviceCode)
                    .addFileParams("files", fileList)
                    .headers("Authorization", "Bearer " + token)
                    .adapt(new ObservableResponse<String>())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            OkGo.<String>post(url)
                    .converter(new StringConvert())
                    .isMultipart(true)
                    .params("userName", nikeName)
                    .params("deviceCode", deviceCode)
                    //.addFileParams("files", fileList)
                    .headers("Authorization", "Bearer " + token)
                    .adapt(new ObservableResponse<String>())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }


    }
}
